<template>
  <div>
    <div id="map" style="width: 100vw; height: 100vh"></div>
  </div>
</template>

<script>
import { default as proj4 } from "proj4";
import * as Cesium from "cesium";
import "cesium/Build/Cesium/Widgets/widgets.css";
import mapData from "@/assets/map/R_FLOWCTLVALVE.json";

export default {
  name: "cesium",
  data() {
    return {
      viewer: null,
    };
  },
  methods: {
    initMap() {
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2ZTgxOGNhZC03NThmLTQ0NzMtOTNlYS1kNmM3YzlmZDU3NTMiLCJpZCI6MTI1NTY3LCJpYXQiOjE2NzY5MDI0MzJ9.ulIEz3NCh2cMEBiHrqIuv9I6icn5KTMMnBdy2wassoM";
      this.viewer = new Cesium.Viewer("map", {
        // 配置项
      });
    },
    tranformCoordinate(x, y) {
      const fromProjection = `PROJCS["Hong Kong 1980 Grid System",GEOGCS["Hong Kong 1980",DATUM["Hong_Kong_1980",SPHEROID["International 1924",6378388,297],TOWGS84[-162.619,-276.959,-161.764,-0.067753,2.243648,1.158828,-1.094246]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4611"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",22.3121333333333],PARAMETER["central_meridian",114.178555555556],PARAMETER["scale_factor",1],PARAMETER["false_easting",836694.05],PARAMETER["false_northing",819069.8],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","2326"]]`;
      const toProjection = `GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]`;
      const newCoordinates = proj4(fromProjection, toProjection, [x, y]);
      return [newCoordinates[0] - 0.0002, newCoordinates[1] - 0.0005]; // 返回数组格式
    },
    getHeightData(mapData) {
      let that = this;
      let arr = [];
      let heightData = [];
      mapData.forEach((feature, index) => {
        let point = that.tranformCoordinate(
          feature.geometry.coordinates[0],
          feature.geometry.coordinates[1]
        );
        arr.push(Cesium.Cartographic.fromDegrees(...point));
      });
      console.log("arr1:", arr);
      const terrainProvider = Cesium.createWorldTerrain();
      const promise = Cesium.sampleTerrain(terrainProvider, 11, arr);
      Promise.resolve(promise).then((updatedPositions) => {
        heightData = updatedPositions;
        console.log("heightData:", heightData);
        let arr = [];
        // let count = 0;
        // lengthArr.forEach((length) => {
        //   let obj = [];
        //   for (let i = 0; i <= length - 1; i++) {
        //     obj.push(heightData[count].height);
        //     count++;
        //   }
        //   arr.push(obj);
        // });
        heightData.forEach((item) => {
          arr.push(item.height);
        });
        console.log("arr2:", arr);
      });
    },
    getCount(mapData) {
      let that = this;
      let countArr = [];
      mapData.forEach((feature, index) => {
        let positions = feature.geometry.coordinates[0];
        let total = 0;
        for (let i = 1; i <= positions.length - 1; i++) {
          total += this.getDistance(positions[i], positions[i - 1]);
        }
        countArr.push(total);
      });
      console.log(countArr);
    },
    // calculateCount(pixel = 100, positions) {
    //   let viewer = this.viewer;
    //   const scene = viewer.scene;
    //   const geodesic = new Cesium.EllipsoidGeodesic();
    //   const width = scene.canvas.clientWidth;
    //   const height = scene.canvas.clientHeight;
    //   const left = scene.camera.getPickRay(
    //     new Cesium.Cartesian2((width / 2) | 0, height - 1)
    //   );
    //   const right = scene.camera.getPickRay(
    //     new Cesium.Cartesian2((1 + width / 2) | 0, height - 1)
    //   );

    //   const globe = scene.globe;
    //   const leftPosition = globe.pick(left, scene);
    //   const rightPosition = globe.pick(right, scene);

    //   console.log("leftPosition:", leftPosition);
    //   console.log("rightPosition:", rightPosition);
    //   if (!Cesium.defined(leftPosition) || !Cesium.defined(rightPosition)) {
    //     return;
    //   }
    //   const leftCartographic =
    //     globe.ellipsoid.cartesianToCartographic(leftPosition);
    //   const rightCartographic =
    //     globe.ellipsoid.cartesianToCartographic(rightPosition);
    //   geodesic.setEndPoints(leftCartographic, rightCartographic);
    //   //1 像素实际距离
    //   let pixelDistance = geodesic.surfaceDistance;

    //   //1 像素实际距离
    //   let sumLength = this.getDisTance(positions);

    //   const sumXY = sumLength / pixelDistance;
    //   const count = sumXY / pixel;

    //   console.log("count:", count);

    //   return count.toFixed(2);
    // },
    // getDisTance(positions) {
    //   let viewer = this.viewer;
    //   let distance = 0;
    //   const scene = viewer.scene;
    //   const globe = scene.globe;
    //   for (let i = 0; i < positions.length - 1; i++) {
    //     /**根据经纬度计算出距离**/
    //     const geodesic = new Cesium.EllipsoidGeodesic();

    //     const start = globe.ellipsoid.cartesianToCartographic(positions[i]);
    //     const end = globe.ellipsoid.cartesianToCartographic(positions[i + 1]);

    //     geodesic.setEndPoints(start, end);
    //     let s = geodesic.surfaceDistance;
    //     //返回两点之间的距离
    //     s = Math.sqrt(Math.pow(s, 2) + Math.pow(start.height - end.height, 2));
    //     distance = distance + s;
    //   }

    //   console.log("distance:", distance);

    //   return distance.toFixed(3);
    // },
    // handleFromDegreesArray(data) {
    //   let arr = [];
    //   data.forEach((item) => {
    //     arr.push(...this.tranformCoordinate(item[0], item[1]));
    //   });
    //   return arr;
    // },
    getDistance(point1, point2) {
      point1 = this.tranformCoordinate(point1[0], point1[1]);
      point2 = this.tranformCoordinate(point2[0], point2[1]);
      let startPosition = new Cesium.Cartesian3.fromDegrees(
        point1[0],
        point1[1]
      );
      let endPosition = new Cesium.Cartesian3.fromDegrees(point2[0], point2[1]);
      let distance = Cesium.Cartesian3.distance(startPosition, endPosition);
      return distance;
    },
  },
  mounted() {
    this.initMap();
    this.getHeightData(mapData.features);
    // this.getCount(mapData.features);
  },
};
</script>
